// module_files.js

import DirModelHolder from '@/js/dir_model_holder.js'


const as_root = { root: true }


function NewModel(id) {
  return { id }
}



function filter_items(items, location) {
  if (items == null || location == null) { return }
  for (let i in items) {
    let item = items[i]
    item.at = location
  }
}


function prepareRequestFQuery({ context, id, location }) {
  let uri = location
  let ref = ""
  let mod = context.state.models[id];
  if (mod != null) {
    ref = mod.uri;
    if (ref == null) { ref = "" }
  }
  return { uri, ref }
}



////////////////////////////////////////////////////////////////////////////////

const state = {

  models: {
    example: {}
  }

}


const getters = {

  model(state) {
    return ({ id }) => {
      let m = state.models[id]
      if (m == null) { m = {} }
      return m
    }
  },

  model_holder(state) {
    return ({ id }) => {
      let m = state.models[id]
      return DirModelHolder.NewHolder(m)
    }
  },

}

const mutations = {

  bind(state, { id }) {
    let m = NewModel(id)
    state.models[id] = m
  },

  unbind(state, { id }) {
    state.models[id] = null;
  },

  updateModel(state, { id, vo }) {
    let older = state.models[id]
    let newer = vo.fquery
    let location = newer.location
    let items = newer.items
    filter_items(items, location)
    let h1 = DirModelHolder.NewHolder(older)
    let h2 = DirModelHolder.NewHolder(newer)
    h1.Import(h2.Export())
  },

}

const actions = {

  fetch(context, { id, location }) {
    let method = 'POST'
    let url = '/api/v1/fquery'
    let fq = prepareRequestFQuery({ context, id, location })
    let data = {
      fquery: fq
    }
    let p = context.dispatch('axios/execute', { method, url, data }, as_root)
    p.then((resp) => {
      let vo = resp.data;
      context.commit('updateModel', { id, vo })
    })
    return p
  },

}




////////////////////////////////////////////////////////////////////////////////

export default {

  name: "files",

  namespaced: true,

  state, getters, mutations, actions,
} 
